import React from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, message, Tooltip, Switch, Input, Select } from 'antd';
import CommonListsIndex from 'src/components/CommonLists/index';
import SearchBar from 'src/components/SearchBar';
import CodeLabel from 'src/components/CodeLabel';
import AuditStatus from 'src/components/AuditStatus';
import { getFeildByTreeData } from 'src/utils/utils';
import { AUDIT, ENABLE_STATUS, COMPONENT_STATUS, VARS_TYPE_LIST } from 'src/utils/constant';
import services from 'src/services/api';
import storage from 'src/utils/storage';
import Modal from 'src/components/Modal/index';
import RelationStrategy from '../relation';
import List from './list';
import Add from './add';

function mapStateToProps(state) {
  return {
    strategy_mode: state.code.strategy_mode || [],
    orgList: state.global.orgList,
  };
}

@connect(mapStateToProps)
class StrategyComponent extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'strategyComponent';
    this.addComponent = Add;
    this.editComponent = '/strategy/component/id/edit';
    this.copyComponent = '/strategy/component/id/copy';
    this.detailComponent = '/strategy/component/id/detail';
    this.listsComponent = List;
    this.state = {
      ...this.state,
      riskTypes: [],
    };
    // if (this.app_id) {
    //   this.queryTableParams.app_id = this.app_id;
    // }
    // if (this.event_id) {
    //   this.queryTableParams.event_id = this.event_id;
    // }
    // if (this.field_id) {
    //   this.queryTableParams.field_id = this.field_id;
    // }
    // if (this.feature_id) {
    //   this.queryTableParams.feature_id = this.feature_id;
    // }
  }
  componentDidMount() {
    const locationState = this.props.history.location;
    if (locationState.state && locationState.state.name) {
      this.queryParams.projectName = locationState.state.name;
    }
    this.freshQueryList();
    // this.getAppCodeList();
    // this.getProductCodeList();
    // this.getRiskTypeList();
    // storage.strategyExport = []; // 首次进入清空storage.strategyExport
  }

  getSearchList = () => {
    return [
      {
        name: 'projectName',
        component: <Input placeholder='项目名称' />,
      },
      {
        name: 'name',
        component: <Input placeholder='组件名称' />,
      },
      {
        name: 'mode',
        component: (
          <Select placeholder='组件类型'>
            {this.props.strategy_mode &&
              this.props.strategy_mode.map((it) => {
                return (
                  <Select.Option value={it.key} key={it.key}>
                    {it.value}
                  </Select.Option>
                );
              })}
          </Select>
        ),
      },
      {
        name: 'createBy',
        component: <Input placeholder='创建人' />,
      },
      {
        name: 'updateBy',
        component: <Input placeholder='修改人' />,
      },
    ];
  };

  // 获取风险类型列表
  getRiskTypeList = () => {
    services.policy.riskTypeList().then((res) => {
      if (res.code === '0') {
        this.setState({
          riskTypes: res.data,
        });
      }
    });
  };

  // 策略导入回调
  onChange = (info) => {
    this.freshQueryList();
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 导入成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 导入失败`);
    }
  };

  // 关联策略
  showRelationStrategy(record) {
    Modal.open({
      title: (
        <>
          关联策略<span style={{ fontSize: 10, color: 'grey', marginLeft: 4 }}>仅展示当前部门拥有权限数据</span>
        </>
      ),
      width: '1000px',
      content: (
        <RelationStrategy
          record={record}
          param={{
            id: record.id,
          }}
        />
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => Modal.close(),
    });
  }

  // 详情
  showDetail = (record) => {
    this.props.history.push(this.replaceUrlForId(this.detailComponent, this.getOpenParam(record)));
  };

  // 复制
  copy = (record) => {
    this.props.history.push(this.replaceUrlForId(this.copyComponent, this.getOpenParam(record)));
  };

  // 表列定义
  getColumns = () => {
    const { orgList } = this.props;
    return [
      {
        title: '所属机构',
        key: 'orgCode',
        dataIndex: 'orgCode',
        width: 150,
        ellipsis: true,
        render: (text) => {
          const name = getFeildByTreeData({
            tree: orgList,
            souceVal: text,
          }).name;
          return (
            <Tooltip title={name} placement='topLeft'>
              <div className='overflowtext'>{name}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '所属项目',
        key: 'projectName',
        dataIndex: 'projectName',
        width: 150,
        ellipsis: true,
        render: (text) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '组件名称',
        key: 'name',
        dataIndex: 'name',
        width: 150,
        ellipsis: true,
        render: (text) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '组件code',
        key: 'code',
        dataIndex: 'code',
        width: 150,
        ellipsis: true,
        render: (text) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '组件类型',
        key: 'mode',
        dataIndex: 'mode',
        width: 150,
        ellipsis: true,
        render: (text) => {
          return (
            <Tooltip title={<CodeLabel code='strategy_mode' value={text} />}>
              <div className='overflowtext'>
                <CodeLabel code='strategy_mode' value={text} />
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '最新可用版本',
        key: 'version',
        dataIndex: 'version',
        width: 130,
        ellipsis: true,
        render: (text) => {
          return text ? <span style={{ color: '#00a600' }}>{'v' + text}</span> : '-';
        },
      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        width: 150,
        ellipsis: true,
        render: (text) => {
          return COMPONENT_STATUS[text];
        },
      },
      {
        title: '关联策略',
        dataIndex: 'refStrategyNums',
        width: 150,
        key: 'refStrategyNums',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Button type='link' onClick={() => this.showRelationStrategy(record)}>
              {text}
            </Button>
          );
        },
      },
      {
        title: '修改时间',
        key: 'updateAt',
        width: 150,
        dataIndex: 'updateAt',
        ellipsis: true,
        render: (text) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '创建人/修改人',
        key: 'createBy',
        dataIndex: 'createBy',
        width: 150,
        ellipsis: true,
        render: (_, record) => {
          var content = !!record.updateBy
            ? `${record.createBy}/${record.updateBy}`
            : `${record.createBy}/${record.createBy}`;
          return (
            <Tooltip title={content} placement='topLeft'>
              {content}
            </Tooltip>
          );
        },
      },
    ];
  };

  // 删除回调
  deleteCb = (record) => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) return;
    if (selectedRowKeys.indexOf(record.strategy_id) !== -1) {
      let newKeys = selectedRowKeys.filter((item) => item !== record.strategy_id);
      let newRows = selectedRows.filter((item) => item.strategy_id !== record.strategy_id);
      if (newKeys.length === 0) this.setState({ currentEventId: '' });
      this.setState(
        {
          selectedRowKeys: newKeys,
          selectedRows: newRows,
        },
        () => {
          const exportMsg = {
            selectedRowKeys: this.state.selectedRowKeys,
            currentEventId: this.state.currentEventId,
          };
          storage.strategyExportMsg = exportMsg;
        },
      );
    }
  };

  render() {
    const ListsComponent = this.listsComponent;
    return (
      <div>
        <SearchBar
          searchList={this.getSearchList()}
          query={this.freshQueryList}
          onChange={this.refreshFilter}
          reset={this.resetListAndSearch}
        />

        <div className='inner-content' style={{ marginTop: '10px' }}>
          <Row type='flex' justify='space-between' align='middle' className='pb-10'>
            <Col span={12}>
              <Button
                type='primary'
                onClick={() => {
                  this.props.history.push('/strategy/component/add');
                }}
              >
                新建组件
              </Button>
            </Col>
          </Row>
          <ListsComponent
            {...this.state}
            {...this.props}
            edit={this.edit}
            scroll={{ x: true }}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            copy={this.copy}
            defaultColumns={this.state.defaultColumns}
            columns={this.getColumns()}
            queryList={this.freshQueryList}
            rowKey='id'
            deleteCb={this.deleteCb}
          />
        </div>
      </div>
    );
  }
}

export default StrategyComponent;
